$(document).ready(function () {
    // 获取ID
    var id = $.getUrlParam("id");
    
    get_product(id);
    $("#editbtn").click(function (e) { 
        edit_product(e);
    });
    $("#delbtn").click(function (e) { 
        del_product(e);
    });
});

function get_product(id) {
    $.ajax({
        type: "GET",
        url: SERVER_PATH + "/product/detail/" + id,
        xhrFields: {withCredentials: true},
        success: function (result) {
            if (result.status) {
                alertBox(result.data.message);
                return false;
            }
            set_product(result.data);
        }
    });
}

function set_product(product) {
    if (!product) {
        return false;
    }

    $("#editid").val(product.id)
    $("#editname").val(product.name)
    $("#editprice").val(product.price)
    $("#editintr").val(product.introduction)
    $("#editamount").val(product.proAmount)
    $("#editclass").val(product.proClass)
    $("#editurl").val(product.imageUrl);
}

function edit_product(e){
        
    var proid = $.getUrlParam("id");
    var proname = $("#editname").val()
    var proprice = $("#editprice").val()
    var prointr = $("#editintr").val()
    var proamount=$("#editamount").val()
    var proclass = $("#editclass").val()
    var prourl = $("#editurl").val();

    $.ajax({
        type: "POST",
        url: SERVER_PATH + "/admin/updateproduct",
        data: {
            "id":proid,
            "name": proname,
            "price": proprice,
            "introduction": prointr,
            "proAmount": proamount,
            "proClass": proclass,
            "imageUrl": prourl
        },
        xhrFields: {withCredentials: true},
        success: function (result) {
            if (result.status) {
                alertBox(result.data.message);
                return false;
            }
            alertBox("修改成功！", function() {
                window.location.href = "change.html";
            });
        }
    });
    
}


function del_product(e){
    var proid = $.getUrlParam("id");
    var proname = $("#editname").val()
    var proprice = $("#editprice").val()
    var prointr = $("#editintr").val()
    var proamount=$("#editamount").val()
    var proclass = $("#editclass").val()
    var prourl = $("#editurl").val();


    $.ajax({
        type: "POST",
        url: SERVER_PATH + "/admin/deleteproduct",
        data: {
            "id":proid,
            "name": proname,
            "price": proprice,
            "introduction": prointr,
            "proAmount": proamount,
            "proClass": proclass,
            "imageUrl": prourl
        },
        xhrFields: {withCredentials: true},
        success: function (result) {
            if (result.status) {
                alertBox(result.data.message);
                return false;
            }
            alertBox("删除成功！", function() {
                window.location.href = "change.html";
            });
        }
    });
    
}
